import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

// 检查后端服务是否可用的工具函数（带重试机制）
export const checkBackendHealth = async (retries: number = 2, delay: number = 500): Promise<boolean> => {
  try {
    const response = await fetch('http://localhost:5000/api/health', {
      timeout: 2000
    });

    if (!response.ok && retries > 0) {
      console.warn(`后端服务检查失败，将重试(${retries}次剩余)...`);
      await new Promise(resolve => setTimeout(resolve, delay));
      return checkBackendHealth(retries - 1, delay * 2);
    }

    return response.ok;
  } catch (error) {
    console.error('后端服务不可用:', error);

    // 如果还有重试次数，进行重试
    if (retries > 0) {
      console.warn(`请求异常，将重试(${retries}次剩余)...`);
      await new Promise(resolve => setTimeout(resolve, delay));
      return checkBackendHealth(retries - 1, delay * 2);
    }

    return false;
  }
}

// 安全获取对象属性的工具函数
export const getNestedProperty = (obj: any, path: string, defaultValue: any = null): any => {
  if (!obj || typeof path !== 'string') {
    return defaultValue;
  }

  const properties = path.split('.');
  let result = obj;

  for (const property of properties) {
    if (result === null || result === undefined) {
      return defaultValue;
    }
    result = result[property];
  }

  return result !== undefined ? result : defaultValue;
}
